/*
    Copyright (C) 2013 maik.jablonski@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jfix.compiler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import jfix.compiler.jsp.Generator;
import jfix.compiler.jsp.Parser;

public class JSPCompiler {

	private static JavaCompiler javaCompiler = new JavaCompiler();

	private Class<?> classType;
	private Object object;
	private File jspFile;
	private long lastModified;

	public JSPCompiler(Class<?> clazz) {
		this.classType = clazz;
		String resource = String.format("/%s.jsp",
				classType.getName().replace(".class", "").replace(".", "/"));
		jspFile = new File(classType.getResource(resource).getFile());
	}

	public Object getObject() {
		if (object == null || lastModified < jspFile.lastModified()) {
			lastModified = jspFile.lastModified();
			object = javaCompiler.eval(getJava());
		}
		return object;
	}

	public String getJSP() {
		try {
			Reader fileReader = new BufferedReader(new InputStreamReader(
					new FileInputStream(jspFile), "UTF-8"));
			char[] jspCode = new char[(int) jspFile.length()];
			fileReader.read(jspCode);
			fileReader.close();
			return new String(jspCode).trim();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public String getJava() {
		try {
			return new Generator(new Parser(getJSP()),
					classType.getSimpleName()).toString();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}